﻿namespace Vdc.Window
{
    using System;
    using System.ComponentModel;
    using System.Drawing.Design;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.Design;

    [ToolboxData("<{0}:Dialog runat=\"server\">[Dialog]</{0}:Dialog>"), Designer(typeof(DialogDesigner)), DefaultProperty("Dialog")]
    public class Dialog : Control, INamingContainer
    {
        private ScriptManagerHelper myScriptManager;
        private string myVersion = "1.0.0.1";

        public Dialog()
        {
            this.ViewState["left"] = 0;
            this.ViewState["top"] = 0;
            this.ViewState["width"] = 0;
            this.ViewState["height"] = 0;
            this.ViewState["opacity"] = 100;
            this.ViewState["visibleonload"] = false;
            this.ViewState["ismodal"] = true;
            this.ViewState["isdraggable"] = true;
            this.ViewState["showclosebutton"] = true;
            this.ViewState["title"] = "";
            this.ViewState["iconpath"] = "";
            this.ViewState["stylefolder"] = "";
            this.ViewState["OnClientInit"] = "";
            this.ViewState["OnClientOpen"] = "";
            this.ViewState["OnClientPreOpen"] = "";
            this.ViewState["OnClientPreClose"] = "";
            this.ViewState["OnClientClose"] = "";
            this.ViewState["OnClientDrag"] = "";
            this.ViewState["zindex"] = 0x63;
            this.ViewState["position"] = Positions.SCREEN_CENTER;
            this.ViewState["DebugMode"] = true;
            this.ViewState["pageopacity"] = 0x19;
        }

        private bool CheckAjaxPageInheritance()
        {
            Type baseType = this.Page.GetType().BaseType;
            while (baseType != null)
            {
                if (baseType.ToString() == "OboutInc.oboutAJAXPage")
                {
                    return true;
                }
                try
                {
                    baseType = Activator.CreateInstance(baseType).GetType().BaseType;
                    continue;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }

        internal static Type GetBaseInterfaceType(Type t)
        {
            if (t.BaseType.ToString().IndexOf("Vdc.Window") == -1)
            {
                return t;
            }
            return GetBaseInterfaceType(t.BaseType);
        }

        private string initScript(string wID, bool includeScriptTags)
        {
            StringBuilder builder = new StringBuilder();
            if (includeScriptTags)
            {
                builder.Append("<script type='text/javascript' >");
            }
            builder.AppendFormat("var {0};", wID);
            builder.AppendFormat("function init{0}()", wID);
            builder.Append("{");
            builder.Append("try");
            builder.Append("{");
            builder.AppendFormat("{0} = new Dialog(", wID);
            builder.AppendFormat("'{0}'", wID);
            builder.Append(",");
            builder.AppendFormat("'{0}'", (this.StyleRootFolder != "") ? this.StyleRootFolder : "wdstyles/window");
            builder.Append(",");
            builder.AppendFormat("'{0}'", (this.Style != "") ? this.Style : "default");
            builder.Append(",");
            builder.AppendFormat("'{0}'", wID + "_container");
            builder.Append(",");
            builder.AppendFormat("'{0}'", wID + "_content");
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.Title);
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.IconPath);
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.Position);
            builder.Append(",");
            builder.AppendFormat("{0}", "function(){" + this.OnClientInit + "}");
            builder.Append(",");
            builder.AppendFormat("{0}", "function(){" + this.OnClientPreOpen + "}");
            builder.Append(",");
            builder.AppendFormat("{0}", "function(){" + this.OnClientOpen + "}");
            builder.Append(",");
            builder.AppendFormat("{0}", "function(){" + this.OnClientDrag + "}");
            builder.Append(",");
            builder.AppendFormat("{0}", "function(){" + this.OnClientPreClose + "}");
            builder.Append(",");
            builder.AppendFormat("{0}", "function(){" + this.OnClientClose + "}");
            builder.Append(",");
            builder.AppendFormat("{0}", this.Left);
            builder.Append(",");
            builder.AppendFormat("{0}", this.Top);
            builder.Append(",");
            builder.AppendFormat("{0}", this.Width);
            builder.Append(",");
            builder.AppendFormat("{0}", this.Height);
            builder.Append(",");
            builder.AppendFormat("{0}", this.Opacity);
            builder.Append(",");
            builder.AppendFormat("{0}", this.PageOpacity);
            builder.Append(",");
            builder.AppendFormat("{0}", this.zIndex);
            builder.Append(",");
            builder.AppendFormat("{0}", this.VisibleOnLoad.ToString().ToLower());
            builder.Append(",");
            builder.AppendFormat("{0}", this.IsModal.ToString().ToLower());
            builder.Append(",");
            builder.AppendFormat("{0}", this.IsDraggable.ToString().ToLower());
            builder.Append(",");
            builder.AppendFormat("{0}", this.ShowCloseButton.ToString().ToLower());
            builder.Append(");");
            builder.Append("}");
            builder.Append("catch(e)");
            builder.Append("{");
            if (this.DebugMode)
            {
                builder.Append("alert('vdc Window init:'+e.toString());");
            }
            builder.Append("}");
            builder.Append("}");
            if (this.myScriptManager.isAjax || this.CheckAjaxPageInheritance())
            {
                builder.AppendFormat("init{0}();", wID);
            }
            else
            {
                builder.AppendFormat("old{0}load = window.onload;", wID);
                builder.Append("window.onload=function(evt)");
                builder.Append("{");
                builder.AppendFormat("if (old{0}load!=null) old{0}load();", wID);
                builder.AppendFormat("init{0}();", wID);
                builder.Append("};");
            }
            if (includeScriptTags)
            {
                builder.Append(" </script> ");
            }
            return builder.ToString();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            string iD = this.ID;
            bool flag = true;
            this.myScriptManager = new ScriptManagerHelper(this);
            try
            {
                this.Page.VerifyRenderingInServerForm(this);
            }
            catch
            {
                flag = false;
            }
            if (!this.myScriptManager.IsInAsyncCallback)
            {
                string str = "";
                string str3 = HttpUtility.HtmlEncode(this.Page.ClientScript.GetWebResourceUrl(GetBaseInterfaceType(base.GetType()), "Vdc.Window.resources.scripts.windowcore.min.js"));
                str = str + "<script type=\"text/javascript\" src=\"" + str3 + "\"></script>";
                writer.Write(str);
                str = "";
                string str4 = HttpUtility.HtmlEncode(this.Page.ClientScript.GetWebResourceUrl(GetBaseInterfaceType(base.GetType()), "Vdc.Window.resources.scripts.dialog.min.js"));
                str = str + "<script type=\"text/javascript\" src=\"" + str4 + "\"></script>";
                writer.Write(str);
                
                //tungns Nếu không nhập styleFolder -> lấy default
                if (this.StyleFolder != "")
                {
                    string b = this.StyleRootFolder + "/" + ((this.Style != "") ? this.Style : "default") + "/" + ((this.Style != "") ? this.Style : "default") + ".css";
                    string a = Vdc.Window.Window.writeCSS(b);
                    writer.Write(a);
                }
                else
                {
                    string b = HttpUtility.HtmlEncode(this.Page.ClientScript.GetWebResourceUrl(GetBaseInterfaceType(base.GetType()), "Vdc.Window.default.css"));
                    string a = Vdc.Window.Window.writeCSS(b);
                    writer.Write(a);
                }
                
                str = "";
                string key = "";
                //tungns Nếu không nhập styleFolder -> lấy default
                if (this.StyleFolder != "")
                {
                    key = this.StyleFolder + "/" + this.Style + ".js";
                    str = str + "<script type='text/javascript' src='" + key + "'></script>";
                    writer.Write(str);
                }
                else
                {
                    key = HttpUtility.HtmlEncode(this.Page.ClientScript.GetWebResourceUrl(GetBaseInterfaceType(base.GetType()), "Vdc.Window.default.js"));
                    str = str + "<script type=\"text/javascript\" src=\"" + key + "\"></script>";
                    writer.Write(str);
                }
                
                str = "<script type='text/javascript'>" + this.Style + "PreloadImage('" + this.StyleFolder + "');</script>";
                if (!flag || this.CheckAjaxPageInheritance())
                {
                    writer.Write(str);
                }
                else
                {
                    this.myScriptManager.RegisterStartupScript(this, key, "if (typeof " + this.Style + "PreloadImage !=\"undefined\") " + this.Style + "PreloadImage('" + this.StyleFolder + "');", true);
                }
            }
            writer.Write("\n\n<!--   vdc Dialog v." + this.myVersion + "  http://www.vdc.com.vn   -->\n\n");
            writer.Write("<div id='{0}'>", iD + "_container");
            writer.Write("<div id='{0}' style='display:none;'>", iD + "_content");
            ExpireManager manager = new ExpireManager();
            switch (manager.checkExpired())
            {
                case 0:
                    writer.Write("<center><div style=\"width:100%;text-align:center;border: 2px solid #cccccc;  font: 8pt verdana; background-color: #eeeeee;\"><a href=\"http://www.vdc.com.vn\">vdc Window</a><br />Evaluation has expired<br /><a href=\"http://www.vdc.com.vn/\">License ...</a></div></center>");
                    writer.Write("<div style='display:none'>");
                    base.Render(writer);
                    writer.Write("</div>");
                    break;

                case 1:
                    base.Render(writer);
                    break;

                case 2:
                    writer.Write("<div style=\"position:absolute;left:0px;top:-42px;text-align:center;border: 2px solid #cccccc; width:150px; height: 10 px;font: 8pt verdana; background-color: #eeeeee;\"><a href=\"http://www.vdc.com.vn\">vdc Window</a><br />Evaluation has expired<br /><a href=\"http://www.vdc.com.vn/\">License ...</a></div>");
                    base.Render(writer);
                    break;
            }
            writer.Write("</div>");
            writer.Write("</div>");
            if (!flag || this.CheckAjaxPageInheritance())
            {
                writer.Write(this.initScript(this.ID, true));
            }
            else
            {
                this.myScriptManager.RegisterStartupScript(this, this.ID, this.initScript(this.ID, false), true);
            }
        }

        [Description("Gets or sets whether error message will show when error occurs.")]
        public virtual bool DebugMode
        {
            get
            {
                return (bool) this.ViewState["DebugMode"];
            }
            set
            {
                this.ViewState["DebugMode"] = value;
            }
        }

        [Description("Gets or sets Height of Dialog."), Category("Position and Size")]
        public virtual int Height
        {
            get
            {
                return (int) this.ViewState["height"];
            }
            set
            {
                this.ViewState["height"] = value;
            }
        }

        [Editor(typeof(UrlEditor), typeof(UITypeEditor)), Description("Gets or sets IconPath of Dialog."), Category("Header Settings")]
        public virtual string IconPath
        {
            get
            {
                return (string) this.ViewState["iconpath"];
            }
            set
            {
                this.ViewState["iconpath"] = value;
            }
        }

        [Description("Gets or sets whether Dialod can be dragged"), Category("Behaviours")]
        public virtual bool IsDraggable
        {
            get
            {
                return (bool) this.ViewState["isdraggable"];
            }
            set
            {
                this.ViewState["isdraggable"] = value;
            }
        }

        [Category("Behaviours"), Description("Gets or sets whether Dialod is modal")]
        public virtual bool IsModal
        {
            get
            {
                return (bool) this.ViewState["ismodal"];
            }
            set
            {
                this.ViewState["ismodal"] = value;
            }
        }

        [Description("Gets or sets Left position of Dialog"), Category("Position and Size")]
        public virtual int Left
        {
            get
            {
                return (int) this.ViewState["left"];
            }
            set
            {
                this.ViewState["left"] = value;
            }
        }

        [Description("Gets or sets script for Dialog Close event."), Category("Events")]
        public virtual string OnClientClose
        {
            get
            {
                return (string) this.ViewState["OnClientClose"];
            }
            set
            {
                this.ViewState["OnClientClose"] = value;
            }
        }

        [Description("Gets or sets script for Window Drag event."), Category("Events")]
        public virtual string OnClientDrag
        {
            get
            {
                return (string) this.ViewState["OnClientDrag"];
            }
            set
            {
                this.ViewState["OnClientDrag"] = value;
            }
        }

        [Category("Events"), Description("Gets or sets script for Dialog Init event.")]
        public virtual string OnClientInit
        {
            get
            {
                return (string) this.ViewState["OnClientInit"];
            }
            set
            {
                this.ViewState["OnClientInit"] = value;
            }
        }

        [Category("Events"), Description("Gets or sets script for Dialog Open event.")]
        public virtual string OnClientOpen
        {
            get
            {
                return (string) this.ViewState["OnClientOpen"];
            }
            set
            {
                this.ViewState["OnClientOpen"] = value;
            }
        }

        [Category("Events"), Description("Gets or sets script for Dialog Pre-Close event.")]
        public virtual string OnClientPreClose
        {
            get
            {
                return (string) this.ViewState["OnClientPreClose"];
            }
            set
            {
                this.ViewState["OnClientPreClose"] = value;
            }
        }

        [Description("Gets or sets script for Dialog Open event."), Category("Events")]
        public virtual string OnClientPreOpen
        {
            get
            {
                return (string) this.ViewState["OnClientPreOpen"];
            }
            set
            {
                this.ViewState["OnClientPreOpen"] = value;
            }
        }

        [Description("Gets or sets Opacity of Dialog."), Category("Displays")]
        public virtual int Opacity
        {
            get
            {
                return (int) this.ViewState["opacity"];
            }
            set
            {
                this.ViewState["opacity"] = value;
            }
        }

        [Category("Displays"), Description("Gets or Sets the Opacity value of filter background")]
        public virtual int PageOpacity
        {
            get
            {
                return (int) this.ViewState["pageopacity"];
            }
            set
            {
                this.ViewState["pageopacity"] = value;
            }
        }

        [Category("Position and Size"), Description("Gets or sets special position for dialog.")]
        public virtual Positions Position
        {
            get
            {
                return (Positions) this.ViewState["position"];
            }
            set
            {
                this.ViewState["position"] = value;
            }
        }

        [Category("Header Settings"), Description("Gets or sets whether the close button is showed.")]
        public virtual bool ShowCloseButton
        {
            get
            {
                return (bool) this.ViewState["showclosebutton"];
            }
            set
            {
                this.ViewState["showclosebutton"] = value;
            }
        }

        [Description("Gets or sets Style."), Category("Initiation")]
        private string Style
        {
            get
            {
                string styleFolder = this.StyleFolder;
                return styleFolder.Substring(styleFolder.LastIndexOf("/") + 1);
            }
        }

        [Description("Gets or sets Folder that contain style for window."), Category("Displays")]
        public virtual string StyleFolder
        {
            get
            {
                return (string) this.ViewState["stylefolder"];
            }
            set
            {
                string relativeUrl = value.Replace(@"\", "/");
                relativeUrl = base.ResolveUrl(relativeUrl);
                this.ViewState["stylefolder"] = relativeUrl;
            }
        }

        [Category("Initiation"), Description("Gets or sets root folder of styles.")]
        private string StyleRootFolder
        {
            get
            {
                string styleFolder = this.StyleFolder;
                if (styleFolder.LastIndexOf("/") == -1)
                {
                    return "";
                }
                return styleFolder.Substring(0, styleFolder.LastIndexOf("/"));
            }
        }

        [Description("Gets or sets Title of Dialog."), Category("Header Settings")]
        public virtual string Title
        {
            get
            {
                return (string) this.ViewState["title"];
            }
            set
            {
                this.ViewState["title"] = value;
            }
        }

        [Description("Gets or sets Top position of Dialog."), Category("Position and Size")]
        public virtual int Top
        {
            get
            {
                return (int) this.ViewState["top"];
            }
            set
            {
                this.ViewState["top"] = value;
            }
        }

        [Description("Gets or sets whether Dialog is visible after page is loaded."), Category("Behaviours")]
        public virtual bool VisibleOnLoad
        {
            get
            {
                return (bool) this.ViewState["visibleonload"];
            }
            set
            {
                this.ViewState["visibleonload"] = value;
            }
        }

        [Category("Position and Size"), Description("Gets or sets Width of Dialog.")]
        public virtual int Width
        {
            get
            {
                return (int) this.ViewState["width"];
            }
            set
            {
                this.ViewState["width"] = value;
            }
        }

        [Category("Displays"), Description("Gets or sets zIndex of Dialog.")]
        public int zIndex
        {
            get
            {
                return (int) this.ViewState["zindex"];
            }
            set
            {
                this.ViewState["zindex"] = value;
            }
        }
    }
}

